package org.hzz.application.handler;

import io.gitee.pkmer.common.collection.CollUtil;
import lombok.extern.slf4j.Slf4j;
import org.hzz.application.command.AddCouponCmd;
import io.gitee.pkmer.designpattern.strategy.AbstractExecuteStrategy;
import org.hzz.promotions.domain.entity.CouponEntity;
import org.hzz.promotions.domain.entity.CouponScopeEntity;
import org.hzz.promotions.domain.service.CouponDomainService;
import lombok.Setter;
import org.hzz.promotions.domain.service.CouponScopeDomainService;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author <a href="mailto:1193094618@qq.com">pkmer</a>
 * <br>
 * <a href = "https://gitee.com/pkmer/sonatype-central-publisher">Code Repository</a>
 * At 2024/8/29
 */
@Slf4j
@Component
public class AddCouponHandler implements AbstractExecuteStrategy<AddCouponCmd,Long> {

    @Setter(onMethod_ = @Autowired)
    private CouponDomainService couponDomainService;


    @Setter(onMethod_ = @Autowired)
    private CouponScopeDomainService scopeDomainService;

    @Override
    public String mark() {
        return AddCouponCmd.MARK;
    }


    @Transactional
    @Override
    public Long executeWithResp(AddCouponCmd cmd) {
        CouponEntity coupon = Converter.INSTANCE.toCouponEntity(cmd);
        couponDomainService.insertCoupon(coupon);

        List<String> scopes = cmd.getScopes();

        if(CollUtil.isNotEmpty(scopes) && cmd.getSpecific()){
            handleCouponScope(scopes, coupon.getId());
        }
        return coupon.getId();
    }

    /**
     * 处理优惠券范围
     * @param scopes 分类的id
     * @param couponId 优惠券Id
     */
    private void handleCouponScope(List<String> scopes, final Long couponId) {
        log.info("该优惠券(id = {})使用的具体课程是：{}",couponId, scopes);

        List<CouponScopeEntity> entities = new ArrayList<>();
        for (String scope : scopes){
            CouponScopeEntity entity = new CouponScopeEntity();
            entity.setCouponId(couponId);
            entity.setBizId(Long.valueOf(scope));
            entities.add(entity);
        }
        scopeDomainService.batchInsertCouponScope(entities);
    }


    @Mapper
    interface Converter{
        Converter INSTANCE = Mappers.getMapper(Converter.class);
        CouponEntity toCouponEntity(AddCouponCmd cmd);
    }
}
